package com.hao.shiro.tools;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 * 摘要
 * @author 97472
 * @version 1.0
 * @date 2021/8/30 10:47
 */
public class DigestsUtil {
    /**
     * 使用的散列算法名
     */
    private static final String HASH_ALGORITHM_NAME = "MD5";
    /**
     * 算法迭代的次数
     */
    private static final Integer ITERATIONS = 256;

    /**
     * 随机获取一个通用的salt值
     * @return
     */
    private static String getGenerateSalt(){
        SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();
        return secureRandomNumberGenerator.nextBytes().toHex();
    }

    /**
     * 获取一个加盐，指定迭代次数的散列算法加密字符串
     * @param input
     * @param salt
     * @return
     */
    private static String sha1(String input,String salt){
        return new SimpleHash(HASH_ALGORITHM_NAME,input,salt,ITERATIONS).toBase64();
//        return new Md5Hash(input,salt,ITERATIONS).toString();
    }

    /**
     * 将指定密码进行加密
     * @param password
     * @return
     */
    public static Map<String,String> encryptPassword(String password){
        String salt = getGenerateSalt();
        password = sha1(password, salt);
        Map<String,String> data = new HashMap();
        data.put("salt",salt);
        data.put("password",password);
        return data;
    }
}
